package com.example.myapplication;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    
    //声明控件
    private EditText etUsername;
    private EditText etPassword;
    private CheckBox cbAgree;
    private Button btnLogin;
    private Button btnRegister;
    private ProgressBar progress_loading;

    //邮箱验证正则表达式
    private static final String EMAIL_REGEX = "^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+\\.[a-zA-Z]{2,}$";
    private Pattern pattern;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate");
        setContentView(R.layout.activity_main);

        //初始化正则表达式
        pattern = Pattern.compile(EMAIL_REGEX);

        //绑定控件
        initViews();

        //设置按钮点击事件
        setButtonListen();

        //为checkBox设置状态变化监视器
        cbAgree.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(@NonNull CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    Toast.makeText(MainActivity.this, "已同意用户协议", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "请同意用户协议", Toast.LENGTH_SHORT).show();
                }
            }
        });

        //为用户名输入框设置内容变化监听
        setUsernameTextChangeListener();

        //为密码输入框设置内容变化监听
        setPasswordFocusChangeListener();
    }

    private void setPasswordFocusChangeListener() {
        etUsername.addTextChangedListener(new TextWatcher() {
            //文本变化时
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                //可用于记录变化前的状态
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //为当前输入文本
                String input = s.toString().trim();
                if (!TextUtils.isEmpty(input) && !isValidEmail(input)) {
                    etUsername.setError("邮箱格式不正确");
                } else {
                    etUsername.setError(null);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                //可用于处理变化后的逻辑
            }
        });
    }

    private void setUsernameTextChangeListener() {
        etUsername.setOnFocusChangeListener((v, hasFocus) -> {
            //获得焦点时的操作
            if (hasFocus) {
                //获得焦点时的操作
                Toast.makeText(MainActivity.this, "请输入密码", Toast.LENGTH_SHORT).show();
            } else {
                //失去焦点时的操作
                String password = etPassword.getText().toString().trim();
                if (password.length() > 0 && password.length() < 6) {
                    etPassword.setError("密码长度不能小于6位");
                } else {
                    etPassword.setError(null);
                }
            }
        });
    }

    private void initViews() {
        etUsername = findViewById(R.id.et_username);
        etPassword = findViewById(R.id.et_password);
        cbAgree = findViewById(R.id.cb_agree);
        btnLogin = findViewById(R.id.btn_login);
        btnRegister = findViewById(R.id.btn_register);
        progress_loading = findViewById(R.id.progress_loading);
        etUsername.setText("415@qq.com");
        etPassword.setText("123456");
        cbAgree.setChecked(true);
    }

    private void setButtonListen() {
        // 登录按钮点击事件
        btnLogin.setOnClickListener(v -> handleLogin());
        // 注册按钮点击事件
        btnRegister.setOnClickListener(v -> handleRegister());
    }

    /**
     * 处理登录逻辑
     */
    private void handleLogin() {
        handleAuthentication(true);
    }

    /**
     * 处理注册逻辑
     */
    private void handleRegister() {
        handleAuthentication(false);
    }

    /**
     * 统一处理登录和注册逻辑
     * @param isLogin true表示登录，false表示注册
     */
    private void handleAuthentication(boolean isLogin) {
        //获取输入内容
        String email = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        boolean isAgree = cbAgree.isChecked();

        //验证输入
        if (!isValidEmail(email)) {
            Toast.makeText(this, "请输入有效的邮箱地址", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(password)) {
            Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
            return;
        }
        if (password.length() < 6) {
            Toast.makeText(this, "密码长度小于六位", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!isAgree) {
            Toast.makeText(this, "请同意用户协议", Toast.LENGTH_SHORT).show();
            return;
        }
        
        //所有验证通过，显示进度条
        progress_loading.setVisibility(View.VISIBLE);
        
        // 根据是登录还是注册显示不同的提示
        final String actionMessage = isLogin ? "登录" : "注册";
        
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        progress_loading.setVisibility(View.GONE);
                        // 获取输入的邮箱
                        String inputEmail = etUsername.getText().toString().trim();
                        String username;
                        
                        // 如果输入的是邮箱格式，提取@前面的部分作为用户名；否则直接使用输入的内容
                        if (inputEmail.contains("@")) {
                            username = inputEmail.substring(0, inputEmail.indexOf("@"));
                        } else {
                            username = inputEmail;
                        }
                        
                        // 检查用户名是否为415
                        if ("415".equals(username)) {
                            Toast.makeText(MainActivity.this, actionMessage + "成功", Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent(MainActivity.this, HomeActivity.class);
                            // 传递完整的邮箱地址用于数据隔离
                            intent.putExtra("username", username);
                            intent.putExtra("email", inputEmail);
                            startActivity(intent);
                            finish(); // 关闭登录页面，防止返回
                        } else {
                            Toast.makeText(MainActivity.this, "用户名必须为415才能" + actionMessage, Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        }).start();
    }
    /**
     * 处理注册逻辑
     */
    private boolean isValidEmail(String email) {
        if (TextUtils.isEmpty(email)) {
            return false;
        }
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "onStart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d(TAG, "onRestart");
    }
}